<?php
namespace backend\controllers;

use backend\models\system\SysConfig;
use Yii;
use backend\controllers\BaseController;
use yii\web\UploadedFile;
use yii\base\Model;
use yii\data\Pagination;
use yii\web\Session;
use backend\models\system\BannerGroup;
use backend\models\system\Banner;
use backend\models\article\Article;
use backend\models\article\Lable;
use backend\models\article\Artlable;
use backend\models\article\User;
use backend\models\article\Comment;
use backend\models\statistics\Statistics;
use backend\models\system\WebnoticeForm;
use backend\models\article\Page;
use yii\base\Object;
/**
 * 运营功能模块
 * @author Yang Zhang
 */
class OperateController extends BaseController
{
    /**
     * @inheritdoc  资讯管理
     */
    public function actionIndex()
    {
        $pages = new Pagination([
            'defaultPageSize' => 5,
            'totalCount' => Article::find()->count(),
        ]);
        $model= new Article;
        $model = $model->getArticle($pages);

        $db  = Artlable::find()->asarray()->all();
		
        return $this->render('index',[
            'artist'=>$model,
            'pages'=>$pages,
            'db'=>$db,
			'label_name'=>'1'
        ]);
    }
    /**
    *   资讯添加页
    */
    public function actionArtadd(){
        $model = new Article();
        $labels = Artlable::find()->asarray()->all();

        return $this->render('artadd',['labels'=>$labels,'model'=>$model]);
    }
    /**
    *   添加资讯
    */
    public $enableCsrfValidation = false;
    public function actionDoartadd(){
        $model = new Article();
        /*开始*/
        $uploadFilename =UploadedFile::getInstance($model, 'article');
        print_r($uploadFilename);die;
        /*结束*/

        //获取session
        $session            = Yii::$app->session;
        $user_id = $session->hasSessionId;
        $db = User::find()->where(['id'=>"$user_id"])->asarray()->one();
        $user_name = $db['username'];
        
        $model->attributes          = Yii::$app->request->post();
        /****图片上传start***/     
        $image = UploadedFile::getInstance($model, 'article_thumb');
        if(!empty($image)){
            $rootPath = "uploads/operate/";
            $ext = $image->getExtension();
            $randName = time() . rand(1000, 9999) . "." . $ext;
            $image->saveAs($rootPath . $randName);
            $model->article_thumb       = $rootPath.$randName;
            $model->user_id             = $user_id;
            $model->user_name           = $user_name;
            $model->article_addtime     = time();
            $rs                         = $model->save();
        }    
        /****图片上传end***/ 
        $last_id = Yii::$app->db->getLastInsertID();
        if(!$last_id)
        {
            $this->error('添加失败', ['operate/artadd']);
        }
        $info = yii::$app->request->post();
        $label_id = $info['label_id'];
        $label_id = explode(',', $label_id);
        foreach($label_id as $k=>$attributes)
        {
            $customer = new Lable();
            $customer->article_id   = $last_id;
            $customer->artlable_id  = $attributes;
            $customer->save();
        }  
        if($rs>0){ 
            $this->success('资讯添加成功！', ['operate/index']);
        }else{
            $this->error('资讯添加失败！', ['operate/artadd']);
        }
    }
    /**
    *   资讯编辑页
    */
    public function actionArtedit(){
            $article_id    = Yii::$app->request->get('article_id');
            $model = new Article();

            $date= Article::find()->where(["article_id"=>"$article_id"])->asarray()->one();
            $info = Artlable::find()->asarray()->all();
            $db = Lable::find()->where(["article_id"=>"$article_id"])->asarray()->all();
            foreach ($db as $key => $value) {
                $lable_id[] = $value['artlable_id'];
                
            }
            $lable_id = implode(',', $lable_id);
            $labels = Artlable::find()->where("artlable_id in ($lable_id)")->asArray()->all();
            foreach ($labels as $key => $val) {
               $label_id[] = $val['artlable_id'];
            }
            $info = Artlable::find()->asarray()->all();
            return $this->render('artedit',['model'=>$model,'info'=>$info,'date'=>$date,'labels'=>$labels,'label_list'=>$label_id]);
    
    }
    /**
    *   资讯修改
    */
    public function actionDoart(){
        //获取session
        $session            = Yii::$app->session;
        $session->open();
        $user_id = $session->hasSessionId;
        $db = User::find()->where(['id'=>"$user_id"])->asarray()->one();
        $user_name = $db['username'];
        $article_id    = Yii::$app->request->post('article_id');
        $model = Article::find()->where(['article_id'=>"$article_id"])->one();
        /****图片上传start***/     
        $image = UploadedFile::getInstance($model, 'article_thumb');
        if(!empty($image)){
            $rootPath = "uploads/operate/";
            $ext = $image->getExtension();
            $randName = time() . rand(1000, 9999) . "." . $ext;
            $image->saveAs($rootPath . $randName);
            $model->article_thumb       = $rootPath.$randName;
        }
            $model->attributes          = Yii::$app->request->post();
            $model->user_id             = $user_id;
            $model->user_name           = $user_name;
            $model->article_updtime     = time();
            $rs                         = $model->save();
            
        /****图片上传end***/ 
        lable::deleteAll('article_id = :age', [':age' =>$article_id]);
        
        $info = yii::$app->request->post();
        $label_id = $info['label_id'];
        $label_id = explode(',', $label_id);
        foreach($label_id as $k=>$attributes)
        {
            $customer = new Lable();
            $customer->article_id  = $article_id;
            $customer->artlable_id  = $attributes;
            $customer->save();
        }  
        if($rs>0){ 
            Yii::$app->getSession()->setFlash('success', '修改成功');
            return $this->redirect('index.php?r=operate/index');
        }else{
            Yii::$app->getSession()->setFlash('error', '修改失败');
            return $this->redirect('index.php?r=operate/artedit');
        }
    }
    /**
    *   资讯发布状态的修改
    */
    public function actionUnpublish(){
        $request = Yii::$app->request;
        $art_id  = $request->post('art_id');
        $is_show = $request->post('is_show');
        if($request->isAjax){
            if($is_show==1){
                $customer   = Article::findOne($art_id);
                $customer->is_show=0;
                $count      = $customer->save();
                 
                if($count>0){
                    echo json_encode(['msg'=>'成功','code'=>1]);
                }else{
                    echo json_encode(['msg'=>'失败','code'=>0]);
                }
            }elseif($is_show==0){    
                $customer = Article::findOne($art_id);
                $customer->is_show=1;               
                $count    = $customer->save();
                if($count>0){
                    echo json_encode(['msg'=>'成功','code'=>1]);
                }else{
                    echo json_encode(['msg'=>'失败','code'=>0]);
                }
            }
        }else{
            die('非法操作');
        }

    }
    /**
    *   资讯发布删除
    */
    public function actionArtdel(){
        $art_id     = Yii::$app->request->post('art_id');
        if(Yii::$app->request->isAjax){
            $model  = Article::findOne($art_id);
            $query  = $model->delete();
            if($query){
                echo json_encode(['msg'=>'删除成功','code'=>'1']);
            }else{
                echo json_encode(['msg'=>'删除失败','code'=>'0']);
            }
        }else{
            die('非法操作');
        }
    }

    /**
    *   资讯搜索
    */
    public function actionArtsearch(){
        $label_name = isset($_POST['artlable_name'])?$_POST['artlable_name']:" ";
        $keywords = isset($_POST['keywords'])?$_POST['keywords']:" ";
        $is_show = isset($_POST['is_show'])?$_POST['is_show']:" ";
        if(!empty($keywords)) $code =" and article_contents like '%$keywords%'";
        if(!empty($is_show)) $code.=" and is_show='$is_show'";
        $model= new Article;
        $pages = new Pagination([
            'defaultPageSize' => 5,
            'totalCount' => $model->ArtCount($label_name,$code),
        ]);
        
        $model = $model->ArtSearch($pages,$label_name,$code);
        $db  = Artlable::find()->asarray()->all();
        return $this->render('index',[
            'artist'=>$model,
            'pages'=>$pages,
            'db'=>$db,
            'label_name'=>$label_name,
            'keywords'=>$keywords,
            'is_show'=>$is_show
        ]);
    }

    /**
     * @inheritdoc  资讯标签管理
     */
    public function actionLabel()
    {
        $pages = new Pagination([
            'defaultPageSize' => 5,
            'totalCount' => Artlable::find()->count(),
        ]);
        $model = new Artlable;
        $model = $model->getLable($pages);
        return $this->render('label',['model'=>$model,'pages'=>$pages]);
    }
    /**
     * @inheritdoc  资讯标签添加
     */
    public function actionAddlabel()
    {
        $model                      =  new Artlable();
        $model->attributes          = Yii::$app->request->post();
        $model->artlable_addtime    = time();
        $rs    = $model->save();
        if($rs>0){ 
            Yii::$app->getSession()->setFlash('success', '添加成功');
            return $this->redirect('index.php?r=operate/label');
        }else{
            Yii::$app->getSession()->setFlash('error', '添加失败');
            return $this->redirect('index.php?r=operate/label');
        }  
    }
    /**
     * @inheritdoc  资讯标签编辑
     */
    public function actionEditlable()
    {
        if(Yii::$app->request->isAjax){
            $model          =  new Artlable();
            $artlable_id    = Yii::$app->request->post('artlable_id');
            $db             = Artlable::find()->where(['artlable_id'=>$artlable_id])->asArray()->One();
            return $this->renderPartial('editlable',['model'=>$model,'db'=>$db]);
        }else{
            
            $artlable_id            = Yii::$app->request->post('artlable_id');
            $model                  = Artlable::find()->where(['artlable_id'=>$artlable_id])->one();
            $model->attributes      = Yii::$app->request->post();
            $model->artlable_uptime = time();
            $rs                     = $model->save();
            if($rs>0){ 
                Yii::$app->getSession()->setFlash('success', '修改成功');
                return $this->redirect('index.php?r=operate/label');
            }else{
                Yii::$app->getSession()->setFlash('error', '修改失败');
                return $this->redirect('index.php?r=operate/label');
            } 
        }
    }

    /**
     * @inheritdoc  资讯标签删除
     */
    public function actionDellable()
    {
        $artlable_id     = Yii::$app->request->post('artlable_id');
        if(Yii::$app->request->isAjax){
            $model  = Artlable::findOne($artlable_id);
            $query  = $model->delete();
            if($query){
                echo json_encode(['msg'=>'删除成功','code'=>'1']);
            }else{
                echo json_encode(['msg'=>'删除失败','code'=>'0']);
            }
        }else{
            die('非法操作');
        }
    }
    /**
     * @inheritdoc  资讯评论管理
     */
    public function actionComment()
    {
        $model = new Comment;
        $pages = new Pagination([
            'defaultPageSize' => 5,
            'totalCount' => $model->CommentCount(),
        ]);
        $data = $model->CommentInfo($pages);
        return $this->render('comment',[
            'model' => $model,
            'pages' => $pages,
            'data' => $data,
        ]);
    }

    /**
     * @inheritdoc  资讯评论搜索
     */
    public function actionComsearch()
    {
        $user_name = Yii::$app->request->post('user_name');
        $comment_content = Yii::$app->request->post('comment_content');
        if(!empty($user_name)) $code =" and edu_comment.user_name like '%$user_name%'";
        if(!empty($comment_content)) $code.=" and comment_content like '%$comment_content%'";
        $model = new Comment;
        $pages = new Pagination([
            'defaultPageSize' => 5,
            'totalCount' => $model->ComCount($code),
        ]);
        $data = $model->ComSearch($code,$pages);
        return $this->render('comment',[
            'model' => $model,
            'pages' => $pages,
            'data' => $data,
            'user_name'=>$user_name,
            'comment_content'=>$comment_content,
        ]);
    }

    /**
     * @inheritdoc  评论状态修改
     */
    public function actionComupdate()
    {
        $request = Yii::$app->request;
        $comment_id  = $request->post('comment_id');

        $comment_status = $request->post('comment_status');
        if($request->isAjax){
            if($comment_status==1){
                $customer   = Comment::findOne($comment_id);
                
                $customer->comment_status=0;
                $count      = $customer->save();
                if($count>0){
                    echo json_encode(['msg'=>'成功','code'=>1]);
                }else{
                    echo json_encode(['msg'=>'失败','code'=>0]);
                }
            }elseif($comment_status==0){    
                $model = Comment::findOne($comment_id);
                $model->comment_status=1;               
                $count    = $model->save();
                if($count>0){
                    echo json_encode(['msg'=>'成功','code'=>1]);
                }else{
                    echo json_encode(['msg'=>'失败','code'=>0]);
                }
            }
        }else{
            die('非法操作');
        }
    }
    /**
     * @inheritdoc  网站公告管理
     */
    public function actionComdel()
    {
        $comment_id     = Yii::$app->request->post('comment_id');
        if(Yii::$app->request->isAjax){
            $model  = Comment::findOne($comment_id);
            $query  = $model->delete();
            if($query){
                echo json_encode(['msg'=>'删除成功','code'=>'1']);
            }else{
                echo json_encode(['msg'=>'删除失败','code'=>'0']);
            }
        }else{
            die('非法操作');
        }
    }
    /**
     * @inheritdoc  网站公告管理
     */
    public function actionWebnotice()
    {
	    $model = new WebnoticeForm();
	    $model->config_type = 20;
	    $data = $model->getValueByType();
        return $this->render('notice',['model'=>$model,'data'=>$data]);
    }

	/**
	 * @inheritdoc  网站公告添加
	 */
	public function actionWebnoticeadd()
	{
		$model = new WebnoticeForm();
		if($model->load(Yii::$app->request->post()) && $model->validate())
		{
			$notice = Yii::$app->request->post("WebnoticeForm");
			SysConfig::saveValue($notice,20);
			$this->success('添加成功！', ['operate/webnotice']);
		}
	}

	/**
	 * @inheritdoc  网站公告修改页面
	 */
	public function actionWebnoticeupd()
	{
		$model = new WebnoticeForm();
		if(Yii::$app->request->isPost){
			$config_id = Yii::$app->request->post("config_id");
			$model->config_id = $config_id;
			$db = $model->getValueByid();
			$model->site_notice = $db['config_value'];
			return $this->renderPartial("webnoticeupd",['model'=>$model]);
		}else{
			$this->redirect(['operate/webnotice']);
		}
	}

	/**
	 * @inheritdoc  网站公告修改
	 */
	public function actionWebnoticeupdate()
	{
		if(Yii::$app->request->isPost)
		{
			$data = Yii::$app->request->post('WebnoticeForm');
			$config_id = $data['config_id'];
			$model = SysConfig::findOne($config_id);
			$model->config_value = $data['site_notice'];
			if($model->save())
			{
				$this->success('修改成功！', ['operate/webnotice']);
			}else
			{
				$this->success('修改失败！', ['operate/webnotice']);
			}
		}
	}

	/**
	 * @inheritdoc  网站公告删除
	 */
	public function actionWebnoticedel()
	{
		if(Yii::$app->request->isPost)
		{
			$config_id = Yii::$app->request->post("config_id");
			$model = SysConfig::findOne($config_id);
			if($model->delete())
			{
				echo 1;//删除成功
			}
			else
			{
				echo 0;//删除失败
			}
		}
		else
		{
			echo 2;//无效请求
		}
	}

    /**
     * @inheritdoc  编辑区管理
     */
    public function actionEdition()
    {
        return $this->render('edition');
    }

    /**
     * @inheritdoc  自定义页面管理
     */
    public function actionDiy()
    {
        $model = new Page;
        $pagination = new Pagination([
            'defaultPageSize' => 10,
            'totalCount' => $model->PageCount(),
        ]);
        $data = $model -> PageSel($pagination);
        return $this->render('diy',[
                        'pagination' => $pagination,
                        'model' => $model,
                        'data' => $data,
                ]);
    }
    /**
     * @inheritdoc  添加自定义页面
     */
    public function actionDiyadd()
    {
        $model = new Page;
        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            $this->success('添加成功!',['operate/diy']);
        } else {
            $this->error('添加失败!',['operate/diy']);
        }
    }
    /**
     * @wwx  删除自定义页面
     */
    public function actionDiydelete()
    {
        $request = Yii::$app->request;
        $id = $request->post("id");
        $model = new Page;
        $Page = $model->findOne($id);
        $res=$Page->delete();
        if($res){
            return $this->ajaxSuccess(1);
        }else{
            return $this->ajaxError(0);
        }
    }
    /**
     * @wwx  修改显示自定义页面
     */
    public function actionDiyupdate()
    {
        $request = Yii::$app->request;
        $model = new Page;
        if($request->post('type') == 'list'){
            $id = $request->post("id");
            $model = $model->findOne($id);
            $data = $this->renderPartial('diyupdate', ['model' => $model,]);
            return $this->ajaxSuccess($data);
        }else{
            $user = yii::$app->user->identity;
            $user = $user->attributes;
            $Page = $request->post("Page");
            $id = $Page['page_id'];
            $model = $model->findOne($id);
            $model ->page_uname = $user['username'];
            if ($model->load($request->post()) && $model->save()) {
                $this->success('修改成功!',['operate/diy']);
            } else {
                $this->error('修改失败',['operate/diy']);
            }
        }
        
    }


    /**
     * @inheritdoc  移动端管理
     */
    public function actionApp()
    {
        return $this->render('app');
    }

    /**
     * @inheritdoc  数据统计---班未军
     */
    public function actionCount()
    {   
        return $this->render('count');
    }
    
    /**
     *数据统计  查询相应的数据---班未军
     */
    public function actionSearchinfo() {
        $model = new Statistics;
        $post = Yii::$app->request->post();
        $arr = $model->getSearch($post);
        echo json_encode($arr);
    }

    /**
     * @inheritdoc  轮播编辑
     */
    public function actionCarousel()
    {
	    $model = new BannerGroup();
	    $banner = new Banner();
        $groups = BannerGroup::find()->with('banner')->asArray()->all();
        return $this->render('carousel',[
            'group'=>$groups,
            'model'=>$model,
            'banner'=>$banner
           ]);
    }
    /**
     * 轮播修改
     */
    public function actionCarouselupdate()
    {
        print_r($_REQUEST);die;

        return $this->render('carousel',$groups);
    }

	/**
	 * @inheritdoc  轮播图片添加
	 */
	public function actionCarouseladd()
	{
		$model = new Banner();

		if($model->load(Yii::$app->request->post()) && $model->validate())
		{

			$model->banner_addtime = time();
			$model->save();

            $this->success('轮播图添加成功！', ['operate/carousel']);
		}
		else
		{
            $this->error('轮播图添加失败！', ['operate/carousel']);
		}
	}

	/**
	 * @inheritdoc  轮播组添加
	 */
	public function actionCarouselgroupadd()
	{
		$model = new BannerGroup();
		if($model->load(Yii::$app->request->post()) && $model->validate())
		{
			$model->group_addtime = time();
			$model->save();
            $this->success('添加轮播组成功', ['operate/carousel']);
		}
		else
		{
            $this->error('添加轮播组失败！', ['operate/carousel']);
		}
	}

	/**
	 * @inheritdoc  轮播图删除
	 */
	public function actionBannerdelete()
	{
		if(Yii::$app->request->isPost)
		{
			$banner_id = Yii::$app->request->post("banner_id");
			$re = Banner::findOne($banner_id)->delete();
			if($re)
			{
				echo 1;//删除成功
			}
			else
			{
				echo 0;//删除失败
			}
		}
	}

	/**
	 * @inheritdoc  轮播图修改页面
	 */
	public function actionBannerupdate()
	{
		if(Yii::$app->request->isPost)
		{
			$banner_id = Yii::$app->request->post("banner_id");
			$model = Banner::findOne($banner_id);
			return $this->renderPartial("bannerupd",['model'=>$model]);
		}
	}

	/**
	 * @inheritdoc  轮播图修改
	 */
	public function actionBannerupd()
	{
		if(Yii::$app->request->isPost)
		{
			$data = Yii::$app->request->post("Banner");
			$model = Banner::findOne($data['banner_id']);
			if(!empty($data['banner_thumb']))
			{
				$model ->attributes = $data;
			}
			else
			{
				$data['banner_thumb'] = $model->oldattributes['banner_thumb'];
				$model ->attributes = $data;
			}

			$re = $model->save();
			if($re)
			{
				$this->success('修改成功', ['operate/carousel']);
			}
			else
			{
				$this->success('修改失败', ['operate/carousel']);
			}
		}
		else
		{
			$this->success('修改失败', ['operate/carousel']);
		}
	}
}
